__author__ = '天祥'

from urllib import request, parse
import urllib
import http.cookiejar
from html.parser import HTMLParser
from flask import request, Flask, render_template, safe_join, send_from_directory
from caculate import cacuMsg

app = Flask(__name__)

hosturl = 'http://210.42.121.132'                   #登陆的主页面
posturl = 'http://210.42.121.132/servlet/Login'     #提交表单的页面
veriurl = 'http://210.42.121.132/servlet/GenImg'    #获取验证码的页面

#获取网站cookie
cookie = http.cookiejar.LWPCookieJar()
cookie_support = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(cookie_support, urllib.request.HTTPHandler)
urllib.request.install_opener(opener)

urllib.request.urlopen(hosturl)            #请求主页面

#解析登陆结果
class resParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.flag = 0
        self.data = ''

    def handle_starttag(self, tag, attrs):
        if(self.get_starttag_text() == r'<font color="red" style="font-size: 12px;">'):
            self.flag = 1

    def handle_data(self, data):
        if(self.flag == 1):
            self.data = data
            self.flag = 0

#登陆
@app.route('/signin', methods=['GET'])
def signIn_form():
    urllib.request.urlretrieve(veriurl, 'static/0.jpg')      #获取验证码图片
    return render_template('Index.html')

@app.route('/signin', methods=['POST'])
def signIn():
    postdata = {                        #表单数据
        'id': request.form['username'],
        'pwd': request.form['password'],
        'xdvfb': request.form['vericode']
    }
    postData = parse.urlencode(postdata).encode('utf-8')            #表单数据编码
    req = urllib.request.Request(posturl)
    req.add_header('User-Agent',            #代理
               "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36")
    req.add_header('Referer',               #引用
               'http://210.42.121.132/')
    rep = urllib.request.urlopen(req, postData)        #提交表单
    text = rep.read().decode('gb2312')

    #获取成绩页面
    fout = open('credit.html', 'w')
    fout.write(opener.open(getCreditUrl()).read().decode('gb2312'))
    fout.close()

    result = resParser()
    result.feed(text)
    if result.data != '':
        return render_template('Index.html', message = result.data)
    else:
        result = cacuMsg()
        return render_template('loadSuccess.html', total_credit = result['总学分：'],
                               total_compulsory_credit = result['必修课总学分：'],
                               total_optional_credit = result['选修课总学分：'],
                               total_professional_credit = result['专业选修课总学分：'],
                               total_public_credit = result['公共选修课总学分：'],
                               total_gpa = result['总绩点：'],
                               average_grade = result['平均成绩：'],
                               class_num = result['课程数目：'],
                               compulsory_gpa = result['必修课绩点：'],
                               compulsory_average = result['必修课平均成绩：'],
                               compulsory_num = result['必修课课程数目：'])

#请求图片等静态文件时采取该方法
@app.route('/<any(css, js, img, fonts, sound):folder>/<path:filename>')
def toplevel_static(folder, filename):
    filename = safe_join(folder, filename)
    cache_timeout = app.get_send_file_max_age(filename)
    return send_from_directory(app.static_folder, filename, cache_timeout=cache_timeout)

#获取成绩页面url
def getCreditUrl():
    return 'http://210.42.121.132/servlet/Svlt_QueryStuScore?year=0&term=&learnType=&scoreFlag=0&t=Wed%20Aug%2012%202015%2010:46:10%20GMT+0800%20(%D6%D0%B9%FA%B1%EA%D7%BC%CA%B1%BC%E4)'        #成绩页面


if __name__ == '__main__':
    app.run(debug=True)